package com.share.device.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.device.domain.Region;
import com.share.device.mapper.RegionMapper;
import com.share.device.service.IRegionService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author zxl
 * @date 2025年03月20日 22:03
 */
@Service
public class RegionServiceImpl extends ServiceImpl<RegionMapper, Region> implements IRegionService {
    /**
     * 根据上级code获取下级数据列表
     *
     * @param parentCode
     * @return
     */
    @Override
    public List<Region> treeSelect(String parentCode) {
        List<Region> regionList = baseMapper.selectList(new LambdaQueryWrapper<Region>().eq(Region::getParentCode, parentCode));
        //不为空
        if (!CollectionUtils.isEmpty(regionList)) {
            regionList.forEach(item -> {
                // 判断是否有子节点
                Long count = baseMapper.selectCount(new LambdaQueryWrapper<Region>().eq(Region::getParentCode, item.getCode()));
                item.setHasChildren(count > 0);
            });
        }
        return regionList;
    }

    /**
     * 获取地区名称
     * @param code 地区编码
     * @return
     */
    @Override
    public String getNameByCode(String code) {
        Region region = baseMapper.selectOne(new LambdaQueryWrapper<Region>().eq(Region::getCode,code).select(Region::getName));
        return null != region ? region.getName() : "";
    }
}
